package com.hujh.android;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class HandlerThreadActivity extends Activity {

	private EditText UITxt;  
    private Button updateUIBtn;  
    private UIHandler UIhandler; 
    private Button handle_runOnUi_thread_btn;
    
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        UITxt = (EditText)findViewById(R.id.handle_t_txt);  
        updateUIBtn = (Button)findViewById(R.id.handle_t_btn);  
        updateUIBtn.setOnClickListener(new View.OnClickListener() {  
              
            public void onClick(View v) {  
                // TODO Auto-generated method stub  
                UIhandler = new UIHandler();  
                UIThread thread = new UIThread();  
                thread.start();  
            }  
        });  
        
        handle_runOnUi_thread_btn = (Button)this.findViewById(R.id.handle_runOnUi_thread_btn);
        handle_runOnUi_thread_btn.setOnClickListener(new View.OnClickListener() {  
            
            public void onClick(View v) {  
            	updateStatus("runOnUi_thread...");
            }
        }); 
    }
    
    private class UIHandler extends Handler{  
        @Override  
        public void handleMessage(Message msg) {  
            // TODO Auto-generated method stub  
            super.handleMessage(msg);  
            Bundle bundle = msg.getData();  
            String color = bundle.getString("color");  
            UITxt.setText(color);  
        }
    }  
    
    private class UIThread extends Thread{  
        @Override  
        public void run() {  
            try {  
                Thread.sleep(3000);  
            } catch (InterruptedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }
            Message msg = new Message();  
            Bundle bundle = new Bundle();  
            bundle.putString("color", "黄色");  
            msg.setData(bundle);  
            HandlerThreadActivity.this.UIhandler.sendMessage(msg);  
              
        }  
    }
    
    public void updateStatus(final String status) {
        // Be a good citizen.  Make sure UI changes fire on the UI thread.
        this.runOnUiThread(new Runnable() {
            public void run() {
                TextView labelView = (TextView) findViewById(R.id.runOnUiThread);
                labelView.setText(status);
            }
        });
    }
    
    
}
